package com.example.demo.service.impl;


import com.example.demo.config.DataSourceContextHolder;
import com.example.demo.config.DynamicRoutingDataSource;
import com.example.demo.entity.Datasource;
import com.example.demo.mapper.DatasourceMapper;
import com.example.demo.service.ChangeDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;


/**
 * fileName:ChangeDataSourceServiceImpl
 * description:
 * author: LJV
 * createTime:2022/4/1 16:27
 * version:1.0.0
 */
@Service
public class ChangeDataSourceServiceImpl implements ChangeDataSourceService {
    @Resource
    private DatasourceMapper dataSourceMapper;

    @Autowired
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    @Override
    public boolean changeDS(String datasourceId) {
        //切到默认数据源
        DataSourceContextHolder.removeDataSource();
        //找到所有的配置
        List<Datasource> dataSourceList = dataSourceMapper.selectList(null);

        //根据数据源id查询数据源信息
        Datasource datasource = dataSourceMapper.selectById(datasourceId);
        if(!ObjectUtils.isEmpty(datasource)){
            System.out.println("已找到数据源,datasourceId是：" + datasource.getDatasourceId());
            //判断连接是否存在，不存在就创建
            dynamicRoutingDataSource.checkCreateDataSource(datasource);
            //切换数据源
            DataSourceContextHolder.setDataSource(datasource.getDatasourceId());
            return true;
        }

       /* if(!CollectionUtils.isEmpty(dataSourceList)){
            for (Datasource dataSource : dataSourceList) {
                if(dataSource.getDatasourceId().equals(datasourceId)){
                    System.out.println("已找到数据源,datasourceId是：" + dataSource.getDatasourceId());
                    //判断连接是否存在，不存在就创建
                    dynamicRoutingDataSource.checkCreateDataSource(dataSource);
                    //切换数据源
                    DataSourceContextHolder.setDataSource(dataSource.getDatasourceId());
                    return true;
                }
            }
        }*/
        return false;
    }
}
